package lancs.mobilemedia.core.ui.controller.commands;

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Display;
import javax.microedition.rms.RecordStoreFullException;

import lancs.mobilemedia.core.ui.controller.AbstractController;
import lancs.mobilemedia.core.ui.controller.ControllerCommand;
import lancs.mobilemedia.core.ui.controller.PhotoController;
import lancs.mobilemedia.core.ui.controller.PhotoViewController;
import lancs.mobilemedia.core.ui.controller.ScreenSingleton;
import lancs.mobilemedia.core.ui.datamodel.ImageData;
import lancs.mobilemedia.core.ui.screens.AddPhotoToAlbum;
import lancs.mobilemedia.core.util.Constants;
import lancs.mobilemedia.lib.exceptions.ImageNotFoundException;
import lancs.mobilemedia.lib.exceptions.ImagePathNotValidException;
import lancs.mobilemedia.lib.exceptions.InvalidImageDataException;
import lancs.mobilemedia.lib.exceptions.NullAlbumDataReference;
import lancs.mobilemedia.lib.exceptions.PersistenceMechanismException;

public class SaveCopiedPhoto implements ControllerCommand {

	public boolean execute(AbstractController controller) {
		try {
			ImageData imageData = null;

			try {
				imageData = controller.getAlbumData().getImageInfo(((PhotoViewController) controller).getImageName());
			} catch (ImageNotFoundException e) {
				e.printStackTrace();
			} catch (NullAlbumDataReference e) {
				e.printStackTrace();
			}
			String photoname = ((AddPhotoToAlbum) controller.getCurrentScreen()).getPhotoName();
			String albumname = ((AddPhotoToAlbum) controller.getCurrentScreen()).getPath();
			controller.getAlbumData().addImageData(photoname, imageData, albumname);

		} catch (InvalidImageDataException e) {
			Alert alert = null;
			if (e instanceof ImagePathNotValidException)
				alert = new Alert("Error", "The path is not valid", null, AlertType.ERROR);
			else
				alert = new Alert("Error", "The image file format is not valid", null, AlertType.ERROR);
			Display.getDisplay(controller.getMidlet()).setCurrent(alert,
					Display.getDisplay(controller.getMidlet()).getCurrent());
			return true;
		} catch (PersistenceMechanismException e) {
			Alert alert = null;
			if (e.getCause() instanceof RecordStoreFullException)
				alert = new Alert("Error", "The mobile database is full", null, AlertType.ERROR);
			else
				alert = new Alert("Error", "The mobile database can not add a new photo", null, AlertType.ERROR);
			Display.getDisplay(controller.getMidlet()).setCurrent(alert,
					Display.getDisplay(controller.getMidlet()).getCurrent());
		}
		ScreenSingleton.getInstance().setCurrentScreenName(Constants.IMAGELIST_SCREEN);
		((PhotoController) controller.getNextController()).showImageList(ScreenSingleton.getInstance()
				.getCurrentStoreName(), false, false);

		return true;
	}
}